package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.model.BoardAccess;
import com.conversationboard.model.Boards;
import com.conversationboard.model.User;
import com.conversationboard.model.exceptions.UserDoesNotExistException;

@WebServlet(name = "CreateBoardControllerServlet", urlPatterns = "/Admin/CreateBoardControllerServlet")
public class CreateBoardControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 2470258794810169900L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		String name = request.getParameter("name");
		String description = request.getParameter("description");
		String userId = request.getUserPrincipal().getName();
		String popularBoardCheckBox = request.getParameter("checkbox2");
		String hiddenBoardCheckBox = request.getParameter("checkbox3");
		String requireRegistrationCheckBox = request.getParameter("checkbox4");
		String adminsAddUsersCheckBox = request.getParameter("checkbox6");
		String allowPollsCheckBox = request.getParameter("checkbox7");
		String noIndexCheckBox = request.getParameter("noindex");
		String logAdminActionsCheckBox = request.getParameter("checkbox8");
		BoardAccess boardAccess = BoardAccess.valueOf(request.getParameter("boardAccess"));
		int sandboxDays = Integer.parseInt(request.getParameter("sandboxDays"));
		int numberOfNewPosts = Integer.parseInt(request.getParameter("numberOfNewPosts"));

		boolean popularBoard = false;

		if (popularBoardCheckBox != null && popularBoardCheckBox.equals("popular")) {
			popularBoard = true;
		}

		boolean hiddenBoard = false;

		if (hiddenBoardCheckBox != null && hiddenBoardCheckBox.equals("hidden")) {
			hiddenBoard = true;
		}

		boolean requireRegistration = false;

		if (requireRegistrationCheckBox != null && requireRegistrationCheckBox.equals("requireRegistration")) {
			requireRegistration = true;
		}

		boolean adminsAddUsers = false;

		if (adminsAddUsersCheckBox != null && adminsAddUsersCheckBox.equals("adminsAddUsers")) {
			adminsAddUsers = true;
		}

		boolean allowPolls = false;

		if (allowPollsCheckBox != null && allowPollsCheckBox.equals("allowPolls")) {
			allowPolls = true;
		}

		boolean noIndex = false;

		if (noIndexCheckBox != null && noIndexCheckBox.equals("true")) {
			noIndex = true;
		}

		boolean logAdminActions = false;

		if (logAdminActionsCheckBox != null && logAdminActionsCheckBox.equals("true")) {
			logAdminActions = true;
		}

		try {

			User user = User.get(userId);

			/*
			 * If users are allowed to create boards, then check if they're
			 * logged in and they pass security checks and bale out if anything
			 * is wrong.
			 */

			if (Configuration.getInstance().isAllowUserBoardCreation()) {
				if (!(user.isLoggedIn() && SecurityChecks.passes(request, user, this))) {
					return;
				}
			} else {
				/*
				 * Otherwise, you need to be a site admin who has passed the
				 * security checks
				 */

				if (!(user.isSiteAdmin() && SecurityChecks.passes(request, user, this))) {
					return;
				}
			}

			int boardId = Boards.create(name, description, boardAccess, popularBoard, requireRegistration, hiddenBoard, adminsAddUsers, allowPolls, noIndex, logAdminActions, sandboxDays,
					numberOfNewPosts);

			/*
			 * If it's a private or invite only board, or if it's a user-created
			 * board give the creator access.
			 */

			if ((boardAccess == BoardAccess.Private) || (boardAccess == BoardAccess.InviteOnly)) {
				user.allowAccessToBoard(boardId);
			}

			/* Similarly, give the creator board admin privileges */

			if (!user.isSiteAdmin()) {
				user.makeBoardAdmin(boardId);
			}

			/* Now refresh the boards cache */

			Boards.refreshCache();

			request.setAttribute("message", "New board successfully created.");
			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
			dispatcher.forward(request, response);

		} catch (UserDoesNotExistException e) {
			throw new ServletException(e);
		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
